package com.punai.config.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.punai.common.bos.KVBO;
import com.punai.common.core.page.TableDataInfo;
import com.punai.config.service.UnitConverService;
import com.punai.config.sqlitedao.ConfigUnitConverRepository;
import com.punai.config.sqlitedomain.ConfigUnitConver;
import com.punai.config.sqlitedomain.vo.ConfigUnitConverVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UnitConverServiceImpl implements UnitConverService {

    @Autowired
    private ConfigUnitConverRepository unitConverRepository;

    @Override
    public TableDataInfo getMainTableData(ConfigUnitConverVo vo) {
        List<ConfigUnitConver> all = unitConverRepository.findAllByModel(vo);
        List<ConfigUnitConverVo> res = new ArrayList<>();
        for (ConfigUnitConver configUnitConver : all) {
            ConfigUnitConverVo re = new ConfigUnitConverVo();
            BeanUtil.copyProperties(configUnitConver,re);
            if(StrUtil.isNotEmpty(re.getKvJson())){
                re.setKvobjStr(re.getKvJson().replaceAll("\\{", "")
                        .replaceAll("}", "")
                        .replaceAll("\"","")
                        .replaceAll(",",";"));
            }
            res.add(re);
        }
        int total = unitConverRepository.countByModel(vo);
        return new TableDataInfo(res, total);
    }

    @Override
    public ConfigUnitConverVo getInfo(ConfigUnitConverVo vo) {
        ConfigUnitConver one = unitConverRepository.findOneById(vo.getId());
        ConfigUnitConverVo res = new ConfigUnitConverVo();
        BeanUtil.copyProperties(one, res);
        if (StrUtil.isNotEmpty(res.getKvJson())) {
            Map<String, Object> map = JSONUtil.toBean(res.getKvJson(), Map.class);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                res.getKvObj().add(new KVBO() {{
                    setKey(entry.getKey());
                    setValue(entry.getValue());
                }});
            }
        }
        return res;
    }

    @Override
    public ConfigUnitConver save(ConfigUnitConverVo vo) {
        return unitConverRepository.save(vo);
    }

    @Override
    public ConfigUnitConver remove(ConfigUnitConverVo vo) {
        return unitConverRepository.delete(vo.getId());
    }
}
